package cn.kduck.module.message.service.sender;

import cn.kduck.module.message.SmsServiceProperties;
import cn.kduck.module.message.service.SmsMessageSender;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Map;

public class TencentSmsMessageSender implements SmsMessageSender {

    private final SmsServiceProperties properties;

    private final String appId;

    private SmsClient client;

    public TencentSmsMessageSender(SmsServiceProperties properties){
        this.properties = properties;
        Map channel = properties.getChannel();
        Map tencentMap = (Map)channel.get("tencent");
        this.appId = String.valueOf(tencentMap.get("appId"));
        Assert.notNull(appId,"腾讯短信服务配置参数错误，缺少配置参数：kduck.module.sms.channel.tencent.appId");

        initClient(properties);
    }

    private void initClient(SmsServiceProperties param) {
        Credential cred = new Credential(properties.getSecretId(), properties.getSecretKey());

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod(HttpProfile.REQ_POST);

        String serverEndpoint = properties.getServerEndpoint();
        if(StringUtils.hasText(serverEndpoint)){
            httpProfile.setEndpoint(serverEndpoint);
        }

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("HmacSHA256");
        clientProfile.setHttpProfile(httpProfile);
//            ap-guangzhou
        client = new SmsClient(cred, "ap-beijing",clientProfile);
    }

    @Override
    public boolean sendMessage(SenderParam param) {

        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppid(appId);
        req.setSign(properties.getSignName());
        req.setTemplateID(param.getTemplateCode());

        String[] params = param.getParams();
        if(params.length > 0){
            String[] formattedParams = new String[params.length];
            for (int i = 0; i < params.length; i++) {
                int paramIndex = params[i].indexOf(":");
                formattedParams[i] = paramIndex >= 0 ? params[i].substring(paramIndex + 1) : params[i];
            }
            req.setTemplateParamSet(formattedParams);
        }


        String[] phoneNumberSet = {"+86" + param.getPhoneNum()};
        req.setPhoneNumberSet(phoneNumberSet);

        req.setSessionContext(""); //用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回
        req.setExtendCode("");
        req.setSenderId("");

        try{
            SendSmsResponse res = client.SendSms(req);
            // 也可以取出单个值，你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
            // System.out.println(res.getRequestId());
            System.out.println(SendSmsResponse.toJsonString(res));
            return true;
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException("短信发送失败：" + param.getPhoneNum(),e);
        }
    }
}
